package kxfang.com.login.ui;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.Nullable;


import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.ToastUtils;
import com.hjq.umeng.Platform;
import com.hjq.umeng.UmengClient;
import com.hjq.umeng.UmengLogin;
import com.orhanobut.hawk.Hawk;


import java.util.List;

import kxfang.com.base.activity.MvvmBaseActivity;
import kxfang.com.base.utils.GsonUtils;
import kxfang.com.base.viewmodel.IMvvmBaseViewModel;
import kxfang.com.common.config.HttpConfig;
import kxfang.com.common.constant.Constant;
import kxfang.com.common.dialog.MessageDialog;
import kxfang.com.common.dialog.WaitDialog;
import kxfang.com.common.router.RoutHub;
import kxfang.com.common.services.BluetoothService;
import kxfang.com.common.utils.ActivityStackManage;
import kxfang.com.common.utils.HawkUtil;
import kxfang.com.common.utils.MyUtils;
import kxfang.com.common.utils.RouterUtils;
import kxfang.com.common.utils.StatusBarUtil;
import kxfang.com.common.utils.Validator;
import kxfang.com.common.views.BaseDialog;
import kxfang.com.http.EasyHttp;
import kxfang.com.http.callback.SimpleCallBack;
import kxfang.com.http.exception.ApiException;
import kxfang.com.login.R;
import kxfang.com.login.bean.AppUser;
import kxfang.com.login.bean.MsgModel;
import kxfang.com.login.databinding.LoginActivityLoginBinding;
import kxfang.com.login.parameter.GetCodePar;
import kxfang.com.common.parameter.LoginPar;



import static kxfang.com.common.constant.Constant.yqID;

@Route(path = RoutHub.PAGER_LOGIN)
public class LoginActivity extends MvvmBaseActivity<LoginActivityLoginBinding, IMvvmBaseViewModel> implements UmengLogin.OnLoginListener {

    GetCodePar getCodePar = new GetCodePar();

    private int type, bs = 2;//bs区分密码登录还是验证码
    private List<String> datasBeanList;
    private boolean isExit = false;//默认是返回上级页面
    private WaitDialog.Builder waitDialog;
    Platform platform;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getIntent().hasExtra("type")) {
            isExit = true;
        }
        if (MyUtils.isServiceWork(this,"kxfang.com.android.service.BluetoothService")){
            stopService(new Intent(this, BluetoothService.class));
        }
        StatusBarUtil.setTopActivityView(this, viewDataBinding.topView);
        thisOnclick();
        ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        ClipData data = cm.getPrimaryClip();
        if (data != null) {
            ClipData.Item item = data.getItemAt(0);
            if (item.getText() != null) {
                yqID = item.getText().toString();
                if (yqID != null) {
                    // 清除剪贴板
                    ClipData clip = ClipData.newPlainText("", "");
                    cm.setPrimaryClip(clip);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    protected IMvvmBaseViewModel getViewModel() {
        return null;
    }

    @Override
    protected int getBindingVariable() {
        return 0;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.login_activity_login;
    }

    @Override
    protected void onRetryBtnClick() {

    }

    //点击账号密码隐藏部分控件显示隐藏控件
    private void thisOnclick() {
        //监听账号输入状态
        viewDataBinding.phoneEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                Log.e("onTextChanged", "onTextChanged: =" + start + " before=" + before + "count=" + count);
                if (start == 10) {
                    mHandler.removeCallbacks(mRunnable);
                    //800毫秒没有输入认为输入完毕
                    mHandler.post(mRunnable);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        viewDataBinding.codeValue.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (start >= 5) {
                    mHandler.removeCallbacks(mRunnable);
                    //800毫秒没有输入认为输入完毕
                    mHandler.postDelayed(mRunnable, 1000);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        viewDataBinding.tvYinshi.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putString("url", Constant.LOAD_WEBVIEWURL.concat("/user/privacyProtocol?type=android"));
            bundle.putString("title", "可心房隐私政策");
            RouterUtils.navigate(RoutHub.WEB_MAIN, bundle, this);

        });
        viewDataBinding.tvYonghu.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putString("url", Constant.LOAD_WEBVIEWURL.concat("/user/serviceProtocol?type=android"));
            bundle.putString("title", "可心房用户服务协议");
            RouterUtils.navigate(RoutHub.WEB_MAIN, bundle, this);

        });
        //账号密码登录
        viewDataBinding.passwordLogin.setOnClickListener(v -> {
            viewDataBinding.loginRelayout.setVisibility(View.VISIBLE);
            viewDataBinding.passwordLogin.setVisibility(View.GONE);
            viewDataBinding.tvLoginTitle.setText("账号密码登录");
            viewDataBinding.tvTishi.setVisibility(View.INVISIBLE);
            viewDataBinding.getCodeText.setVisibility(View.GONE);
            viewDataBinding.codeValue.setHint("请输入密码(最少8位，数字+字母组合)");
            viewDataBinding.codeValue.setText("");
            viewDataBinding.codeValue.setInputType(129);
            viewDataBinding.codeValue.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});
            bs = 1;
        });
        //手机快捷登录
        viewDataBinding.loginPhone.setOnClickListener(v -> {
            viewDataBinding.loginRelayout.setVisibility(View.GONE);
            viewDataBinding.passwordLogin.setVisibility(View.VISIBLE);
            viewDataBinding.tvLoginTitle.setText("手机快捷登录");
            viewDataBinding.tvTishi.setVisibility(View.VISIBLE);
            viewDataBinding.getCodeText.setVisibility(View.VISIBLE);
            viewDataBinding.codeValue.setHint("请输入验证码");
            viewDataBinding.codeValue.setText("");
            viewDataBinding.codeValue.setInputType(InputType.TYPE_CLASS_NUMBER);
            viewDataBinding.codeValue.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
            bs = 2;
        });

        viewDataBinding.loginPwd.setOnClickListener(v -> {

            Intent intent = new Intent(this, PwdLoginActivity.class);
            startActivity(intent);
        });
        viewDataBinding.textSee.setOnClickListener(v -> {
            RouterUtils.navigate(RoutHub.PAGER_MAIN);
        });

        viewDataBinding.wechatLogin.setOnClickListener(v -> {
            type = 1;
            platform = Platform.WECHAT;
            UmengClient.login(this, platform, this);
        });
        viewDataBinding.qqLogin.setOnClickListener(v -> {
            type = 2;
            //QQ登录
            platform = Platform.QQ;
            UmengClient.login(this, platform, this);

        });
        viewDataBinding.loginButton.setOnClickListener(v -> {
            if (!Validator.isMobile(viewDataBinding.phoneEdit.getText().toString().trim())) {
                ToastUtils.showShort("请输入正确的手机号码");
                return;
            }
            if (!viewDataBinding.checkboxBtn.isChecked()) {
                ToastUtils.showShort("请阅读协议");
                return;
            }
            if ("".equals(viewDataBinding.codeValue.getText().toString())) {
                ToastUtils.showShort("验证码不能为空");
                return;
            }

            waitDialog = new WaitDialog.Builder(this);
            waitDialog.setMessage("登录中").show();

            login();
        });
        viewDataBinding.getCodeText.setOnClickListener(v -> {
            if (Validator.isMobile(viewDataBinding.phoneEdit.getText().toString().trim())) {
                getCode();
            } else
                ToastUtils.showShort("请输入正确的手机号码");
        });
        //关闭界面
        viewDataBinding.deleteActivity.setOnClickListener(v -> {
            finish();
        });
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(LoginActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            } catch (Exception e) {

            }
        }
    };
    private Runnable mRunnable = () -> mHandler.sendEmptyMessage(1);


    //获取验证码
    private void getCode() {
        if (!Validator.isMobile(viewDataBinding.phoneEdit.getText().toString().trim())) {
            ToastUtils.showShort("请输入正确的手机号码");
            return;
        }
        timer.start();
        getCodePar.setPhone(viewDataBinding.phoneEdit.getText().toString());
        getCodePar.setVeriCode(1);
        getCodePar.setPromotersID(yqID);
        loadCode(getCodePar);
    }

    CountDownTimer timer = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            viewDataBinding.getCodeText.setText("已发送(" + millisUntilFinished / 1000 + ")");
            viewDataBinding.getCodeText.setEnabled(false);
        }

        @Override
        public void onFinish() {
            viewDataBinding.getCodeText.setEnabled(true);
            viewDataBinding.getCodeText.setText("获取验证码");
        }
    };

    //请求验证码
    private void loadCode(GetCodePar par) {
        EasyHttp.post(HttpConfig.loadCode)
                .cacheKey(HttpConfig.loadCode.concat(LoginActivity.class.getSimpleName()))
                .upJson(GsonUtils.toJson(par))
                .execute(new SimpleCallBack<MsgModel>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(ApiException e) {

                    }

                    @Override
                    public void onSuccess(MsgModel msgModel) {
                        if (msgModel.getCode() != 200) {
                            ToastUtils.showShort(msgModel.getMsg());
                        }
                    }
                });

    }


    /**
     * 登录
     */
    private void login() {
        LoginPar par = new LoginPar();
        par.setPhone(viewDataBinding.phoneEdit.getText().toString());
        if (bs == 2) {
            par.setYzm(viewDataBinding.codeValue.getText().toString());
        } else {
            par.setPwd(viewDataBinding.codeValue.getText().toString());
        }
        par.setPromotersID(yqID);
        par.setPersonType(1);
        EasyHttp.post(HttpConfig.login)
                .cacheKey(HttpConfig.login.concat(LoginActivity.class.getSimpleName()))
                .upJson(GsonUtils.toJson(par))
                .execute(new SimpleCallBack<AppUser>() {
                    @Override
                    public void onError(ApiException e) {

                    }

                    @Override
                    public void onSuccess(AppUser appUser) {
                        HawkUtil.deleteAll();
                        //持久化用户信息Id
                        if (appUser.getThirdInfo() != null && appUser.getThirdInfo().size() > 0) {
                            Hawk.put("thirdInfo", appUser.getThirdInfo());
                        }
                        Hawk.put("ctype", appUser.getCtype());
                        Hawk.put("phone", appUser.getPhone());
                        Hawk.put(Constant.HAWK_USER_INFO, appUser.getId());
                        Hawk.put("head", appUser.getHead());
                        Hawk.put("alias", appUser.getAlias());
                        Hawk.put("statu", appUser.getStatu());
                        Hawk.put("isnew", appUser.getIsNew());
                        Hawk.put("IsRecruitor", appUser.getIsRecruitor());
                        Hawk.put("IsJober", appUser.getIsJober());
                        Hawk.put("IndustryValue", appUser.getIndustryValue());
                        Hawk.put(Constant.IM_TOKEN_SP, appUser.getImtoken());
                        Hawk.put(Constant.IM_UESR_ID, appUser.getImid());
                        RouterUtils.navigate(RoutHub.PAGER_MAIN);
                        finish();

                    }

                    @Override
                    public void onCompleted() {
                        waitDialog.dismiss();
                    }
                });


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 友盟登录回调
        UmengClient.onActivityResult(this, requestCode, resultCode, data);
    }

    /**
     * {@link UmengLogin.OnLoginListener}
     */

    /**
     * 授权成功的回调
     *
     * @param platform 平台名称
     * @param data     用户资料返回
     */
    @Override
    public void onSucceed(Platform platform, UmengLogin.LoginData data) {
        // 判断第三方登录的平台
        switch (platform) {
            case QQ:
                type = 2;
                break;
            case WECHAT:
                type = 1;
                break;
            default:
                break;
        }
        if (!"".equals(data.toString())) {
            LoginPar par = new LoginPar();
            par.setPersonType(8);//8==三方登录
            par.setAlias(data.getName());
            par.setHead(data.getAvatar());
            par.setThirdID(data.getId());
            par.setThirdType(type);//1微信  2QQ
            snafang(par);
        }

//        Glide.with(this)
//                .load(data.getAvatar())
//                .circleCrop()
//                .into(mLogoView);

//        ToastUtils.showShort("昵称：" + data.getName() + "\n" + "性别：" + data.getSex());
//        ToastUtils.showShort("id：" + data.getId());
//        ToastUtils.showShort("token：" + data.getToken());
    }

    /**
     * 授权失败的回调
     *
     * @param platform 平台名称
     * @param t        错误原因
     */
    @Override
    public void onError(Platform platform, Throwable t) {
        ToastUtils.showShort("第三方登录出错：" + t.getMessage());
    }

    /**
     * 授权取消的回调
     *
     * @param platform 平台名称
     */
    @Override
    public void onCancel(Platform platform) {
        ToastUtils.showShort("取消第三方登录");
    }


    /**
     * 第三方登录
     *
     * @param par
     */
    private void snafang(LoginPar par) {
        EasyHttp.post(HttpConfig.login)
                .cacheKey(HttpConfig.login.concat(LoginActivity.class.getSimpleName()))
                .upJson(GsonUtils.toJson(par))
                .execute(new SimpleCallBack<AppUser>() {
                    @Override
                    public void onError(ApiException e) {

                    }

                    @Override
                    public void onSuccess(AppUser appUser) {
                        if (appUser.getThirdInfo().size() <= 0) {
                            Intent intent = new Intent(LoginActivity.this, BindPhoneActivity.class);
                            intent.putExtra("ThirdType", par.getThirdType());
                            intent.putExtra("ThirdID", par.getThirdID());
                            startActivity(intent);
                            finish();
                        } else {
                            Hawk.delete(Constant.HAWK_USER_INFO);
                            Hawk.delete("ctype");
                            Hawk.delete("phone");
                            Hawk.delete("head");
                            Hawk.delete("alias");
                            Hawk.delete("thirdInfo");
                            Hawk.delete("statu");
                            Hawk.delete("IsRecruitor");
                            Hawk.delete("IsJober");
                            Hawk.put("phone", appUser.getPhone());
                            Hawk.put("ctype", appUser.getCtype());
                            Hawk.put(Constant.HAWK_USER_INFO, appUser.getId());
                            Hawk.put("head", appUser.getHead());
                            Hawk.put("alias", appUser.getAlias());
                            if (appUser.getThirdInfo() != null && appUser.getThirdInfo().size() > 0) {
                                Hawk.put("thirdInfo", appUser.getThirdInfo());
                            }
                            Hawk.put("statu", appUser.getStatu());
                            Hawk.put("IsRecruitor", appUser.getIsRecruitor());
                            Hawk.put("IsJober", appUser.getIsJober());
                            Hawk.put(Constant.IM_TOKEN_SP, appUser.getImtoken());
                            Hawk.put(Constant.IM_UESR_ID, appUser.getImid());
                            RouterUtils.navigate(RoutHub.PAGER_MAIN);
                            finish();
                        }

                    }

                    @Override
                    public void onCompleted() {
                        waitDialog.dismiss();
                    }
                });

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isExit) {
                finish();
                return true;
            }
                new MessageDialog.Builder(this)
                        .setTitle("温馨提示")
                        .setMessage("确定要退出程序吗？")
                        .setCancel("取消")
                        .setConfirm("确定")
                        .setAutoDismiss(true)
                        .setListener(new MessageDialog.OnListener() {
                            @Override
                            public void onConfirm(BaseDialog dialog) {
                                ActivityStackManage.popAll();
                            }

                        }).show();

                return false;
            }
            return super.onKeyDown(keyCode, event);
        }
}

